package service

import (
	"crypto/rand"
	"encoding/base64"
	"go-web/config"
	"go-web/model"
	"go-web/repository"
	"strings"
	"time"
)

func generateShortID(n int) string {

	b := make([]byte, n)
	rand.Read(b)
	return strings.TrimRight(base64.URLEncoding.EncodeToString(b), "=")[:n]
}

func CreateShortLink(originalURL string) (model.ShortLink, error) {
	var link model.ShortLink
	for {
		id := generateShortID(6)
		link = model.ShortLink{ShortLink: id, OriginalURL: originalURL}
		err := repository.SaveShortLink(&link)
		if err == nil {
			break
		}
	}

	return link, nil
}

func ResolveShortLink(shortID string) (model.ShortLink, error) {
	// 1. 尝试从 Redis 取值
	url, err := config.Redis.Get(config.Ctx, "short:"+shortID).Result()
	if err == nil {
		// 命中缓存，返回
		return model.ShortLink{
			ShortLink:   shortID,
			OriginalURL: url,
		}, nil
	}

	// 2. Redis 未命中 → 查数据库
	link, err := repository.GetOriginalURLByShortID(shortID)
	if err != nil {
		return link, err
	}

	// 3. 回写 Redis 缓存（设置过期时间 24 小时）
	config.Redis.Set(config.Ctx, "short:"+shortID, link.OriginalURL, 24*time.Hour)

	// 4. 继续记录访问次数
	_ = repository.IncrementClick(shortID)

	return link, nil
}
